//
//  YFRecordVideoRackController.m
//  Victor
//
//  Created by Coollang on 2017/8/16.
//  Copyright © 2017年 coollang. All rights reserved.
//

#import "YFRecordVideoRackController.h"
#import "TrackVideo.h"
#import "NSDate+FormateString.h"
#import "Masonry.h"
#import "UIColor+Extension.h"
#import "YFRecordVideoCell.h"
#import "JCVideoPlayer.h"
#import "YFPlayVideoController.h"
#import "YFAlertHelper.h"

static const CGFloat kAnimationDuration = 0.35f;
static const CGFloat kBottomBarHeight = 64.0f;

NSString * const kTrackRecorddelete = @"kTrackRecorddeleteNotifation";

@interface YFRecordVideoRackController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIButton *trashItem;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewConstraint;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, strong) NSMutableArray *videoDataSource;


@property (nonatomic, strong) UIBarButtonItem *backItem;

@property (nonatomic, strong) UIBarButtonItem *editItem;

/** 是否是编辑状态 */
@property (nonatomic, assign) BOOL isEditing;


@end

@implementation YFRecordVideoRackController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configNavigationBar];
    [self configuerFlowlayout];
    [self updateVideoDataSource];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor colorWithHex:0xeaeaea];
}

- (void)configNavigationBar {
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemClick:)];
    self.backItem = backItem;
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleDone target:self action:@selector(rightItemClick:)];
    self.editItem = rightBarItem;
    self.navigationItem.leftBarButtonItem = backItem;
    self.navigationItem.rightBarButtonItem = rightBarItem;
    self.title = @"Video list";
}

- (void)configuerFlowlayout {
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"YFRecordVideoCell" bundle:nil] forCellWithReuseIdentifier:@"YFRecordVideoCell"];
    
    [self.collectionView registerClass:[YFRecordHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YFRecordHeadView"];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.flowLayout.minimumLineSpacing = 8;
    self.flowLayout.minimumInteritemSpacing = 4;
    self.flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 15, 10);
    self.flowLayout.headerReferenceSize = CGSizeMake(kYFScreenWidth, 44);
    CGFloat leftMargin = 10;
    NSInteger col = 4;
    CGFloat itemWH = (kYFScreenWidth - leftMargin * 2 - (col - 1) * self.flowLayout.minimumInteritemSpacing) / (CGFloat)col;
    self.flowLayout.itemSize = CGSizeMake(itemWH, itemWH);
    
}

- (void)backItemClick:(UIBarButtonItem *)sender {
    if (!self.isEditing){
        [self dismissViewControllerAnimated:YES completion:nil];
    }else {
        BOOL allVideoItemSelected = [self hasAllOfVideoItemsSelected];
        if (allVideoItemSelected) {
            self.backItem.title = @"Select all";
        } else {
            self.backItem.title = @"Deselect all";
        }
        [[RLMRealm defaultRealm] beginWriteTransaction];
        for (NSArray *videoArr in self.videoDataSource) {
            for (TrackVideo *video in videoArr) {
                video.isSelected = !allVideoItemSelected;
            }
        }
        [[RLMRealm defaultRealm] commitWriteTransaction];
        
        [self.collectionView reloadData];
        
        self.trashItem.enabled = [self hasItemSelected] > 0;
    }
}

- (void)rightItemClick:(UIBarButtonItem *)sender {
    self.trashItem.enabled = NO;
    self.isEditing = !self.isEditing;
    if (self.isEditing){
        [self showOrHideEditBottomBar:NO];
        self.backItem.title = @"Select all";
        [self.backItem setImage:nil];
        self.editItem.title = @"Cancel";
        self.collectionView.allowsMultipleSelection = YES;
    }else {
        [self showOrHideEditBottomBar:YES];
        self.collectionView.allowsMultipleSelection = NO;
        self.editItem.title = @"Edit";
        [self.backItem setImage:[UIImage imageNamed:@"返回"]];
        self.backItem.title = @"";
        if (self.videoDataSource.count > 0){
            [[RLMRealm defaultRealm] beginWriteTransaction];
            for (NSArray *videoArr in self.videoDataSource) {
                for (TrackVideo *video in videoArr) {
                     video.isSelected = NO;
                }
            }
            [[RLMRealm defaultRealm] commitWriteTransaction];
        }
    }
    [self.collectionView reloadData];
}

- (void)showOrHideEditBottomBar:(BOOL)hide {
    
    [UIView animateWithDuration:kAnimationDuration delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.7 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.bottomViewConstraint.constant = hide ? 0:kBottomBarHeight;
        [self.view layoutIfNeeded];
    } completion:nil];
}

- (IBAction)trashItemClick:(UIButton *)sender {
    __weak typeof(self) weakSelf = self;
    
    [YFAlertHelper showTwoAlertController:self Title:NSLocalizedString(@"Confirm to Delete？", nil) message:NSLocalizedString(@"The video cannot be recovered once deleted.", @"视频删除后将无法找回!") cancelTitle:NSLocalizedString(@"Cancel", nil) defalutTitle:NSLocalizedString(@"Delete", nil) defaultBtnStyle:UIAlertActionStyleDestructive cancelAction:^(UIAlertAction *action) {
         [self rightItemClick:self.editItem];
    } defalutAction:^(UIAlertAction *action) {
        RLMRealm *realm = [RLMRealm defaultRealm];
        [realm beginWriteTransaction];
        for (NSArray *videoArr in self.videoDataSource) {
            for (TrackVideo *video in videoArr) {
                if (video.isSelected) {
                    [video removeVideoImage];
                    [video removeVideo];
                    [realm deleteObject:video];
                }
            }
        }
        [realm commitWriteTransaction];
        self.trashItem.enabled = NO;
        [weakSelf updateVideoDataSource];
        [self rightItemClick:weakSelf.editItem];
        [[NSNotificationCenter defaultCenter] postNotificationName:kTrackRecorddelete object:nil];
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.videoDataSource.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.videoDataSource[section] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    YFRecordVideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YFRecordVideoCell" forIndexPath:indexPath];
    TrackVideo *videoItem = self.videoDataSource[indexPath.section][indexPath.row];
    [cell configuerRecordVideoCell:videoItem isedit:self.isEditing];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    YFRecordHeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YFRecordHeadView" forIndexPath:indexPath];
    
    TrackVideo *videoItem = [self.videoDataSource[indexPath.section] firstObject];
    
    NSString *dayStr = [videoItem.creatDate formateYearAndMonth];
//    NSString *dayKey = self.videoDict.allKeys[indexPath.section];
    headView.dayStrLabel.text = dayStr;
    
    return headView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *groupArr = self.videoDataSource[indexPath.section];
    if (_isEditing){
        if (indexPath.row < [self.videoDataSource[indexPath.section] count]) {
            TrackVideo *video = groupArr[indexPath.row];
            [video toggleChecked];
            YFRecordVideoCell *cell = (YFRecordVideoCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
            [cell configuerRecordVideoCell:video isedit:self.isEditing];
        }
        self.trashItem.enabled = [self hasItemSelected] > 0;
        
        if ([self hasAllOfVideoItemsSelected]) {
            self.backItem.title = @"Deselect all";
        } else {
            self.backItem.title = @"Select all";
        }
    }else{
        // 跳转到视频播放
//        JCVideoPlayer *videoPlayVc = [[JCVideoPlayer alloc] initWithNibName:@"JCVideoPlayer" bundle:nil];
//        videoPlayVc.videoFiles = groupArr;
//        videoPlayVc.index = indexPath.row;
//        [self presentViewController:videoPlayVc animated:YES completion:nil];
        
        YFPlayVideoController *playVc = [[YFPlayVideoController alloc] initWithNibName:@"YFPlayVideoController" bundle:nil];
        playVc.videoFiles = groupArr;
        playVc.index = indexPath.row;
        [self presentViewController:playVc animated:YES completion:nil];
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Deselect item at indexPath: %@",indexPath);
    
    if (_isEditing) {
        if (indexPath.row < [self.videoDataSource[indexPath.section] count]) {
            TrackVideo *video = self.videoDataSource[indexPath.section][indexPath.row];
            [video toggleChecked];
            YFRecordVideoCell *cell = (YFRecordVideoCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
            [cell configuerRecordVideoCell:video isedit:self.isEditing];
        }
        self.trashItem.enabled = [self hasItemSelected] > 0;
        
        if ([self hasAllOfVideoItemsSelected]) {
            self.backItem.title = @"Deselect all";
        } else {
            self.backItem.title = @"Select all";
        }
    }
}

- (void)updateVideoDataSource {
    RLMResults *results = [[User getLastUser].trackVideos sortedResultsUsingKeyPath:@"creatDate" ascending:NO];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (TrackVideo *video in results) {
        NSString *creatDay = [video.creatDate year_month_day_dateString];
        if ([dict.allKeys containsObject:creatDay]) {
            [dict[creatDay] addObject:video];
            //            [dict[creatDay] insertObject:video atIndex:0];
        }else {
            NSMutableArray *arrM = [NSMutableArray arrayWithObject:video];
            [dict setObject:arrM forKey:creatDay];
        }
    }
    self.videoDataSource = [NSMutableArray arrayWithArray:dict.allValues];
    [self.videoDataSource sortUsingComparator:^NSComparisonResult(NSArray *_Nonnull obj1, NSArray * _Nonnull obj2) {
        
        return [[[obj2.lastObject creatDate] year_month_day_dateString] compare:[[obj1.lastObject creatDate] year_month_day_dateString]];
    }];
    [self.collectionView reloadData];
}

- (BOOL)hasAllOfVideoItemsSelected
{
    // 是否全部被选择
    BOOL hasAllVideoItemsSelected = YES;
    for (NSArray *videoArr in self.videoDataSource) {
        for (TrackVideo *video in videoArr) {
            if (!video.isSelected) {
                hasAllVideoItemsSelected = NO;
                return hasAllVideoItemsSelected;
            }
        }
    }
    return hasAllVideoItemsSelected;
}

- (BOOL)hasItemSelected
{
    if ([self.videoDataSource count] > 0) {
        for (NSArray *videoArr in self.videoDataSource) {
            for (TrackVideo *video in videoArr) {
                if (video.isSelected) {
                    return YES;
                }
            }
        }
    }
    return NO;
}

- (NSMutableArray *)videoDataSource {
    if (_videoDataSource == nil){
        _videoDataSource = [NSMutableArray array];
    }
    return _videoDataSource;
}

@end

@implementation YFRecordHeadView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]){
        UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 6, kYFScreenWidth, 38)];
        bottomView.backgroundColor = [UIColor whiteColor];
        [self addSubview:bottomView];
        UILabel *dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, bottomView.bounds.size.width - 20, bottomView.bounds.size.height)];
        dayLabel.font = [UIFont systemFontOfSize:14];
        dayLabel.textColor = [UIColor colorWithHex:0x999999];
        self.dayStrLabel = dayLabel;
        [bottomView addSubview:self.dayStrLabel];
        self.backgroundColor = [UIColor colorWithHex:0xeaeaea];
    }
    return self;
}

@end
